package net.net23.sysdent;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.GridLayout;
import java.util.ArrayList;

import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.event.InternalFrameEvent;

import net.net23.sysdent.handlers.InternalFrameHandler;

public abstract class PropertiesInternalFrame extends JInternalFrame {

	private static final long serialVersionUID = -7450035194567178856L;
	private JLabel messages;

	public PropertiesInternalFrame(String title, int width, int height) {
		setLayout(new BorderLayout());
		setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
		addInternalFrameListener(new InternalFrameHandler() {
			@Override
			public void internalFrameClosing(InternalFrameEvent e) {
				closeDialog();
			}
		});
		setTitle(title);
		WindowUtility.center(this, width, height);
	}

	public void closeDialog() {
		dispose();
	}

	public void build(PropertiesFields fields, JButton... buttons) {
		createLabels(fields.getLabels());
		createFields(fields.getComponents());
		createButtons(buttons);
	}

	private void createLabels(ArrayList<JLabel> labels) {
		JPanel panel = new JPanel(new GridLayout(labels.size(), 1, 5, 5));
		for (JLabel label : labels) {
			panel.add(label);
		}
		add(panel, BorderLayout.WEST);
	}

	private void createFields(ArrayList<JComponent> components) {
		JPanel panel = new JPanel(new GridLayout(components.size(), 1, 5, 5));
		for (JComponent component : components) {
			panel.add(component);
		}
		add(panel, BorderLayout.CENTER);
	}

	private void createButtons(JButton[] buttons) {
		JPanel panel = new JPanel(new BorderLayout());
		JPanel _panel = new JPanel(new GridLayout(1, 2, 2, 2));
		for (JButton jButton : buttons) {
			_panel.add(jButton);
		}
		panel.add(new JLabel(""), BorderLayout.CENTER);
		panel.add(_panel, BorderLayout.EAST);

		messages = new JLabel("  ");
		messages.setHorizontalAlignment(JLabel.CENTER);
		panel.add(messages, BorderLayout.SOUTH);

		add(panel, BorderLayout.SOUTH);
	}

	public void setError(String error, Component requestField) {
		messages.setForeground(Color.red);
		messages.setText(error);
		if (requestField != null) {
			requestField.requestFocus();
		}
	}

}
